<template>
  <el-drawer v-model="state.show" direction="rtl" :size="state.size" :title="state.title" class="q-drawer">
    <template #default v-if="state.show">
      <div class="el-loading-mask" v-if="state.loading">
        <div class="el-loading-spinner">
          <svg class="circular" viewBox="0 0 50 50">
            <circle class="path" cx="25" cy="25" r="20" fill="none"></circle>
          </svg>
        </div>
      </div>
      <slot />
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="onCancel">取 消</el-button>
        <el-button type="primary" @click="onConfirm" :loading="state.okButtonLoading">确 定</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup>
import { useElementSize } from '@vueuse/core'

const emits = defineEmits(['register', 'ok', 'cancel'])

const state = reactive({
  show: false,
  size: 0,
  title: '',
  okButtonLoading: false,
  loading: false
})

const { width } = useElementSize(document.documentElement)

const onCancel = () => {
  emits('cancel')
}
const onConfirm = () => {
  emits('ok')
}

watch(
  () => width.value,
  val => {
    if (val > 0) {
      state.size = width.value - 200
    }
  },
  { immediate: true }
)

const testMethod = val => {
  console.log('testMethod: ' + val)
}

const initData = data => {
  // console.log(data)
}

const openDrawer = ({ title }) => {
  state.show = true
  state.title = title || 'Drawer'
}

const closeDrawer = () => {
  state.show = false
}

const setOkButtonLoading = loading => {
  state.okButtonLoading = loading
}

const setLoading = loading => {
  state.loading = loading
}

emits('register', { testMethod, initData, openDrawer, closeDrawer, setOkButtonLoading, setLoading })
</script>

<style lang="scss">
.q-drawer {
  .el-drawer__body {
    padding: 16px;
    position: relative;
  }

  .el-drawer__header {
    margin-bottom: 0;
    height: 80px;
    padding: 0 16px;
  }
}
</style>
